package com.buluo.pipeline;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import com.buluo.repository.BuluoDao;
import com.luobo.entity.News;

@Component
public class WenTiPipeLine implements Pipeline {

	@Resource
	private BuluoDao buluoDao;
	
	@Override
	public void process(ResultItems map, Task task) {
    	String title = map.get("title");
    	if(title == null){return;}
    	String content = map.get("content");
    	
    	String dateStr = map.get("date");
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    	Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
		}
    	
		String show = map.get("id");
		
    	News news = new News();
    	news.setGame(3);
    	news.setDate(date);
    	news.setTitle(title);
    	news.setContent(content);		
    	news.setShow(show);
    	
    	String regex = "http://img1.gamedog.cn\\S*(.jpg)|(.png)";
    	Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(content);
		String imgUrl = "";
		if(m.find()){
			imgUrl = m.group(0).replace("img1", "mimg1");
		}
		news.setIcon(imgUrl);
		System.out.println(imgUrl);
    	System.out.println(news.getContent());
    	
    	buluoDao.saveQuestion(news);
    
    	System.out.println("【" + news.getTitle() + "】爬取完成");
	}

}
